//
//  PlayManager.m
//  MusicDemo
//
//  Created by xalo on 16/6/16.
//  Copyright © 2016年 Mario. All rights reserved.
//

#import "PlayManager.h"
@interface PlayManager()
@property (nonatomic,strong)AVPlayer *player;//播放器
@property (nonatomic,strong)NSTimer *timer;//定时器
@end

@implementation PlayManager
+(instancetype)sharedManager{
    static PlayManager *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[PlayManager alloc]init];
    });
    return handle;
}

- (AVPlayer *)player{
    if (!_player) {
        _player = [[AVPlayer alloc]init];
    }
    return _player;
}
- (NSTimer *)timer{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    return _timer;
}

//暂停
- (void)pauseMusic{
    [self.player pause];
    [self closeTimer];
}
//播放
- (void)playMusic{
    [self.player play];
    [self startTimer];
}
//准备去播放
-  (void)prepareToPlayMusicWithUrl:(NSString *)url{
    
    //如果网址为空，不执行任何操作
    if (!url) {
        return;
    }
    //判断当前有没有正在播放的Item
    if (self.player.currentItem) {
        //移除观察者
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }
    
    //创建一个item
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
    
    //观察item的加载状态
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //替换当前item
    [self.player replaceCurrentItemWithPlayerItem:item];
    
    
    //通知传值
    //监测当前歌曲播放完成自动跳到下一首
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playMusicEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    
}
//自动切歌事件（通知的）
- (void)playMusicEnd{
    if ([self.delegate respondsToSelector:@selector(playToNextMusic)]) {
        [self.delegate playToNextMusic];
        //移除通知
        [[NSNotificationCenter defaultCenter]removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
      
    }
 
}

//观察者事件
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    //得到属性改变后的状态
    AVPlayerItemStatus status = [change[@"new"] integerValue];
    switch (status) {
        case AVPlayerItemStatusUnknown:
            NSLog(@"未知错误");
            break;
        case AVPlayerItemStatusReadyToPlay:
            //调用播放方法
            [self playMusic];
            NSLog(@"准备播放");
            break;
        case AVPlayerItemStatusFailed:
            NSLog(@"错误");
            break;
            
        default:
            break;
    }
}
//获取歌曲总时长
- (NSInteger)fetchTotalTime{
    //获取当前播放歌曲的总时长
    CMTime time = self.player.currentItem.duration;
    //播放秒数 = time.value/time.timescale
    if (time.timescale == 0) {
        return 0;
    }
    return time.value/time.timescale;
}
//获取当前播放的时间
- (NSInteger)fecthCurrentTime{
    //获取当前播放时间
    CMTime time = self.player.currentItem.currentTime;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value/time.timescale;
}
//获取当前播放进度
- (CGFloat)fetchProgressValue{
    return [self fecthCurrentTime]/(CGFloat)[self fetchTotalTime];
}
//将秒数转换成00：00的格式
- (NSString *)changeSecondsTime:(NSInteger)time{
    NSInteger min = time/60;
    NSInteger sec = time%60;
    
    return [NSString stringWithFormat:@"%.2ld:%.2ld",min,sec];
}

//快进快退
- (void)playMusicWithSlideValue:(CGFloat)progress{

    //滑动前先暂停播放
    [self pauseMusic];
    [self.player seekToTime:CMTimeMake([self fetchTotalTime]*progress, 1) completionHandler:^(BOOL finished) {
        
        if (finished) {
            
            [self playMusic];
        }
    }];
}
//定时器方法
- (void)timerAction{
//    NSLog(@"当前播放时间%ld",(long)[self fetchTotalTime]);
    
    
    if ([self.delegate respondsToSelector:@selector(playManagerDelegateFetchTotalTime:currentTime:progress:)]) {
       
        NSString *totalTime   = [self changeSecondsTime:[self fetchTotalTime]];//总时间
        NSString *currentTime = [self changeSecondsTime:[self fecthCurrentTime]];//当前时间
        CGFloat progress      = [self fetchProgressValue];//当前进度
        //实现协议方法
        [self.delegate playManagerDelegateFetchTotalTime:totalTime currentTime:currentTime progress:progress];
    }
    
}
//开启定时器
- (void)startTimer{
    [self.timer fire];
}
//关闭定时器
- (void)closeTimer{
    [self.timer invalidate];
    //失效后置空播放器
    self.timer = nil;
}
//是否正在播放
- (BOOL)isPlaying{
    if (self.player.rate == 0) {
        return NO;
    }else{
        return YES;
    }
}









@end
